<?php
// +----------------------------------------------------------------------
// | 杭州十禾信息科技有限公司
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2015 http://www.shelpe.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: LeePuman <ysyzlsm@163.com>
// +----------------------------------------------------------------------

/**
 * 关键词事件
 * 目前只支持的对关键词进行批量添加、删除、调整出价、调整匹配模式
 */
Class KeywordEvent extends NewzanAction
{
    /**
     * 关键词操作
     * @param  array  $postkeywords 需要操作的关键列表
     * @return array  $result       提交之返回关键次相关信息
     */
    public function keywordsUpdate($postkeywords)
	{
        $update_keywords  = array();
        $delete_keywords  = array();
        $add_keywords     = array();
        $word_okid_map    = array();
        $result           = array();
        $keywordMdl       = new KeywordModel;

        $user_id = $this->me['user_id'];

        if($postkeywords) {
            // 获取所有选择的推广计划id
            // $campaign_iids = array_unique(array_column($postkeywords, 'campaign_id'));
            // 获取所有选择的推广组id
            // $adgroup_iids = array_unique(array_column($postkeywords, 'adgroup_id'));

            foreach ($postkeywords as $key => $keyword) {
                $action = $keyword['action'];
                switch($action){
                    //调价
                    case 'adjust' :
                        //set price
                        $new_price = isset($keyword['new_price']) ? $keyword['new_price'] : $keyword['price'];
                        $old_price = $keyword['price'];
                        $new_mobile_price = isset($keyword['new_mobile_price']) ? $keyword['new_mobile_price'] : $keyword['mobile_price'];
                        $old_mobile_price = $keyword['mobile_price'];

                        if($new_price != $old_price || (isset($keyword['new_matchscope']) && $keyword['new_matchscope'] != $keyword['machescope'])) {
                            $update_keywords[$keyword['adgroup_id']][$key] = array(
                                    'word' => $keyword['word'],
                                    'max_price' => $new_price,
                                    'matchscope' => isset($keyword['new_matchscope']) ? ($keyword['new_matchscope'] == 2 ? 4 : $keyword['new_matchscope']) : ($keyword['machescope'] == 2 ? 1 : $keyword['machescope']), // 2016-01-28 By Kungu TODO 由于直通车去除中心匹配（2），讲所有中心匹配改为广泛匹配（4） 
                                    'keyword_id' => $key
                            );

                            if((int)$keyword['default_mobile_price'] === 0) {
                                $update_keywords[$keyword['adgroup_id']][$key]['mobile_is_default_price'] = 0;
                                $update_keywords[$keyword['adgroup_id']][$key]['max_mobile_price'] = $new_mobile_price;
                            }
                        }
                        break;
                    // 删除
                    case 'delete':
                        if($key > 0) {
                            $delete_keywords[$keyword['campaign_id']][$key] = $key;
                        } else {
                            //TODO , 这个方法应该在model中处理好
                            //if not on api then just delete it on local storage
                            M("keywords")->where("keyword_id = " . $key)->delete();
                            $result[$key] = array(
                                    'status' => "deleted",
                                    'keyword_id' => $key,
                                    'action' => 'delete',
                            );
                        }
                        break;
                    // 加词
                    case 'add':
                        $add_keywords[$keyword['adgroup_id']][] = array(
                                'max_price' => isset($keyword['new_price']) ? $keyword['new_price'] : $keyword['price'],
                                'matchscope' => isset($keyword['new_machescope']) ? $keyword['new_machescope'] : 4,
                                'word' => $keyword["word"]
                        );
                        $word_okid_map[$keyword['word']] = $key;
                        break;
                }
            }

            $resp = array();
            // 处理删除词
            if(count($delete_keywords)) {
                foreach ($delete_keywords as $campaign_id => $keywords) {
                    if(count($keywords)) {
                        $tmp = $keywordMdl->deleteKeywords($keywords , $campaign_id);
                        $resp = array_merge($resp, $tmp);
                    }
                }
            }

            foreach($resp as $r) {
                $result[strval($r["keyword_id"])] = array(
                    'status' => "deleted",
                    'keyword_id' => $r["keyword_id"],
                    'action' => 'delete',
                );
            }
            
            // unset($resp);
            $resp = array();
            if (count($update_keywords)) {
                foreach ($update_keywords as $adgroup_id => $keywords) {
                    if(count($keywords)) {
                        $tmp = $keywordMdl->updateKeywords($adgroup_id , $keywords);
                        $resp = array_merge($resp, $tmp);
                    }
                }
            }

            foreach($resp as $k => $r) {
                $result[ strval($r["keyword_id"]) ] = array(
                    'status' => "adjusted",
                    'keyword_id' => $r["keyword_id"],
                    'action' => 'adjust',
                    'price' => $r['price'],
                    'word' => $k,
                    'matchscope' => $r['matchscope'],
                    'mobile_is_default_price' => $r['mobile_is_default_price'],
                    'max_mobile_price' => $r['max_mobile_price']
                );
            }
            
            // unset($resp);
            $resp = array();
            if(count($add_keywords)) {
                foreach ($add_keywords as $adgroup_id => $keywords) {
                    if(count($keywords)) {
                        $tmp = $keywordMdl->addKeywords($this->me['user_id'] , $adgroup_id , $keywords);
                        $resp = array_merge($resp, $tmp);
                    }
                }
            }

            foreach($resp as $k => $r) {
                $result[ strval( $word_okid_map[$k] ) ] = array(
                    'action' => 'add',
                    'status' => 'added',
                    'keyword_id' => $r['keyword_id'],
                    'word' => $k,
                );
            }
        }
        
        if($result) {
            import('@.Library.KeywordCache');
            $keywordCache = new KeywordCache($user_id, $result, $postkeywords);
            $keywordCache->handle();
        }

        return $result;
	}

    /**
     * 批量获取关键词实时排名服务
     * @param  array     $condition  提交过来的关键词
     * @return array     $result     返回结果
     */
    public function keywordsRealRank($condition)
    {
        // 是否将实时排名写入本地数据库
        $insert_db = (isset($condition['adgroup']) || (isset($condition['product_id']) && is_numeric($condition['product_id']))) ? true : false;
        $keywordMdl = new KeywordModel();
        foreach($condition['keywords'] as &$keyword) {
            if($keyword['word'] && $keyword['keyword_id']) {
                $keyword['rank'] = $keywordMdl->getCurrRank(
                                            $keyword['word'],
                                            isset($keyword['itemId']) ? $keyword['itemId'] : $condition['product_id']
                                        );
                $keyword['rank'] = $keyword['rank'] ? : '>100';
            }
        }

        if($insert_db) {
            self::_insertRealRankDB($condition, isset($condition['adgroup_id']) ? true : false);
        }

        return $condition['keywords'];
    }

    /**
     * 将实时排名写入数据库
     * @param  array    $condition    参数
     * @return
     */
    private function _insertRealRankDB($condition, $type = false)
    {
        if($type == false) {
            $adgroup_id = M('adgroups')
                            ->where(array(
                                'num_iid'=>$condition['product_id']
                                ))
                            ->getField('adgroup_id');  
        }
            

        $insertData = array();
        $deleteData = array();
        $sql = 'INSERT INTO rpt_keyword_real_rank (keyword_id,adgroup_id,ravgpos) VALUES ';
        foreach ($condition['keywords'] as $keyword) {
            // $insertData[] = array(
            //         'keyword_id' => $keyword['keyword_id'],
            //         'adgroup_id' => $adgroup_id,
            //         'ravgpos' => $keyword['rank']
            //     );
            if($type)
                $adgroup_id = $keyword['adgroup_id'];
            $insertData[] = "(".$keyword['keyword_id'].",".$adgroup_id.",'".$keyword['rank']."')";
            $deleteData[] = $keyword['keyword_id'];
        }

        if($deleteData) {
            M('rpt_keyword_real_rank')->where(array(
                    'not in',
                    implode(',', $deleteData)
                ))->delete();

            // $rptKeywordRealRankMdl->addAll($insertData);
            $sql .= implode(',', $insertData).' ON DUPLICATE KEY UPDATE ravgpos = VALUES(ravgpos)';
            M()->execute($sql);
            return true;
        }

        return false;
    }
}
